﻿using System.Linq;
using System.Web.Http;
using Enferno.Public.Web.Components.Server.Managers;
using Enferno.Public.Web.Components.Server.ViewModels;

namespace Enferno.Public.Web.Components.Server.Controllers
{
    [RoutePrefix("api/shoppingbasket")]
    public class ShoppingBasketController : ApiController
    {
        private readonly BasketManager _basketManager;

        public ShoppingBasketController()
        {
            _basketManager = new BasketManager();
        }

        [Route("ping")]
        [HttpGet]
        public string Ping()
        {
            return "pong";
        }

        [Route("get")]
        [HttpGet]
        public BasketViewModel Get()
        {
            return _basketManager.GetBasket(Request);
        }

        [Route("{basketId}/deleteitem")]
        [HttpPost]
        public BasketViewModel DeleteItem(int basketId, DeleteModel deleteModel)
        {
            return _basketManager.DeleteItem(basketId, deleteModel.LineNo);
        }

        [Route("{basketId}/additem")]
        [HttpPost]
        public BasketViewModel AddItem(int basketId, BasketItemViewModel item)
        {
            return _basketManager.AddItem(basketId, item);
        }

        [Route("{basketId}/updateitem")]
        [HttpPost]
        public BasketViewModel UpdateItem(int basketId, BasketItemViewModel item)
        {
            return _basketManager.UpdateItem(basketId, item);
        }

        [Route("{basketId}/applyDiscount")]
        [HttpPost]
        public PromotionApplicationResultViewModel ApplyDiscount(int basketId, DiscountModel discountModel)
        {
            var updatedBasket = _basketManager.ApplyDiscount(basketId, discountModel.DiscountCode);

            //try to find the resulting promotion
            var promotion =
                updatedBasket.Promotions.SingleOrDefault(p => p.DiscountCode == discountModel.DiscountCode);

            return new PromotionApplicationResultViewModel {AppliedPromotion = promotion, Basket = updatedBasket};
        }

        [Route("{basketId}/removePromotion")]
        [HttpPost]
        public BasketViewModel RemovePromotion(int basketId, PromotionModel promotionModel)
        {
            var updatedBasket = _basketManager.RemovePromotion(basketId, promotionModel.PromotionId, promotionModel.ResetDiscountCode);

            return updatedBasket;
        }
    }
}
